package com.waimai1.waimai.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.waimai1.waimai.common.BaseContext;
import com.waimai1.waimai.common.R;
import com.waimai1.waimai.common.Utils;
import com.waimai1.waimai.dto.CreatePPOrderDto;
import com.waimai1.waimai.entity.MyOrder;
import com.waimai1.waimai.exception.EnumException;
import com.waimai1.waimai.exception.NotErrorException;
import com.waimai1.waimai.service.FlService;
import com.waimai1.waimai.service.MyOrderService;
import com.waimai1.waimai.service.WepayService;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.*;

@RestController
@RequestMapping("/fl")
@ResponseBody
public class FlController {
    @Autowired
    private FlService flService;
    @Autowired
    private MyOrderService myOrderService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WepayService wepayService;
    @PostMapping("/addHuafei")
    public R<Object> addHuafei(@RequestBody Map<String, Object> map) {
        String method = map.get("method").toString();
        map.remove("method");
        return R.success(flService.getData(map, method));
    }


    @PostMapping("/getArrayData")
    public R<List<Map>> getArrayData(@RequestBody Map<String, Object> map) {
        return R.success(flService.getArrayData(map));
    }

    @PostMapping("/getProductList")
    public R<List<Map>> getProductList(@RequestBody Map<String, Object> map) {
        //官方此函数响应很慢，在此使用Redis缓存，另写函数来更新Redis
        long size = redisTemplate.opsForList().size("FLProductList");
        if(size != 0){
            // 从Redis获取字符串列表
            List<String> jsonStrings = redisTemplate.opsForList().range("FLProductList", 0, -1);
            // 将字符串列表转换回List<Map>
            List<Map> maps = new ArrayList<>();
            for (String jsonString : jsonStrings) {
                maps.add(JSON.parseObject(jsonString, Map.class));
            }
            return R.success(maps);
        }
        List<Map> maps = flService.getArrayData(map);
        // 使用Fastjson将Map转换为JSON字符串
        String[] jsonStrings = maps.stream().map(JSON::toJSONString).toArray(String[]::new);
        redisTemplate.opsForList().leftPushAll("FLProductList", jsonStrings);
        return R.success(maps);
    }

    @PostMapping("/getMapData")
    public R<Object> getMapData(@RequestBody Map<String, Object> map) {
        String method = map.get("method").toString();
        map.remove("method");
        Map<String, Object> res = (Map<String, Object>) flService.getData(map, method);

        System.out.println("================================================================");
        System.out.println(res);
        System.out.println("================================================================");

        if (!"0".equals(res.get("code").toString())) {
            throw new NotErrorException(1008, res.get("code") + (String) res.get("message"));
        }
        String result= (String) res.get("result");
        Map parsedObject = JSON.parseObject(result, Map.class);
        return R.success(parsedObject);
    }

    //创建myorder福禄订单
    @PostMapping("/createFLOrder")
    public R<Object> createFLOrder(@RequestBody MyOrder myOrder) throws Exception {
        //创建订单和详情单
        myOrder.setStatus(Utils.STATUS_WAIT_PAY);
        if(BaseContext.getopenId()==null) {
            throw new NotErrorException(1007, "openid not available");
        }
        myOrder.setOpenid(BaseContext.getopenId());
        myOrder.setAcid(BaseContext.getAcid());
        if (myOrderService.save(myOrder)) {
            //添加延时关单功能
            int delayTime = 5 *60* 1000;
            redisTemplate.opsForZSet().add("cancelOrder", myOrder.getOutTradeNo(), System.currentTimeMillis() + delayTime);
            return R.success("创建订单成功");
        }
        throw new NotErrorException(1007, "创建订单失败");
    }

    //测试回调  https://sunny4.free.idcfengye.com/fl/notify
    @PostMapping("/notify")
    public R<Object> notify(@RequestBody Map<String, Object> argsMap)  {
        System.out.println("================================================================");
        String orderStatus = (String) argsMap.get("order_status");
        String customerOrderNo = (String) argsMap.get("customer_order_no");
        LambdaQueryWrapper<MyOrder> myOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        myOrderLambdaQueryWrapper.eq(MyOrder::getOutTradeNo, customerOrderNo);
        MyOrder myOrder = myOrderService.getOne(myOrderLambdaQueryWrapper);
        if(myOrder == null){
            throw new NotErrorException(1008, "订单不存在");
        }
        switch (orderStatus) {
            case "success":
                myOrder.setHwStatus("充值成功");
                break;
            case "failed:":
                myOrder.setHwStatus("充值失败");
                //自动退款，不在人工审核
                wepayService.allRefund(myOrder);
                myOrder.setStatus(Utils.STATUS_REFUNDED);
                break;
            case "processing":
                myOrder.setHwStatus("处理中");
                break;
            case "untreated":
                myOrder.setHwStatus("等待处理");
                break;
            default:
                throw new NotErrorException(1008, "订单状态错误");
        }

        myOrderService.updateById(myOrder);
        return R.success(1);
    }
    //查询订单详情
    @PostMapping("/getFLOrderDetail")
    public R<Object> getFLOrderDetail(@RequestBody Map<String, Object> map) {
        LambdaQueryWrapper<MyOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MyOrder::getOutTradeNo, map.get("customer_order_no"));
        MyOrder order = myOrderService.getOne(queryWrapper);

        String method = map.get("method").toString();
        map.remove("method");
        Map<String, Object> res = (Map<String, Object>) flService.getData(map, method);

        System.out.println("================================================================");
        System.out.println(res);
        System.out.println("================================================================");

        if (!"0".equals(res.get("code").toString())) {
            throw new NotErrorException(1008, res.get("code") + (String) res.get("message"));
        }
        String result= (String) res.get("result");
        Map parsedObject = JSON.parseObject(result, Map.class);
        String status = (String) parsedObject.get("order_state");
        Map<String, Object> resultMap = new HashMap<>();
        switch (status) {
            case "success":
                order.setHwStatus("充值成功");
                Object cards = parsedObject.get("cards");//若卡密有卡信息则设置
                if(cards!=null){
                    resultMap.put("cards", cards);
                }
                break;
            case "failed":
                order.setHwStatus("充值失败");
                //自动退款，不在人工审核
                wepayService.allRefund(order);
                order.setStatus(Utils.STATUS_REFUNDED);
                break;
            case "processing":
                order.setHwStatus("处理中");
                break;
            case "untreated":
                order.setHwStatus("等待处理");
                break;
            default:
                throw new NotErrorException(1008, "订单状态错误");
        }
        myOrderService.updateById(order);
        resultMap.put("hwStatus", order.getHwStatus());
        return R.success(resultMap);
    }
}
